//导入express框架
var express = require("express");
var request = require('request');
var mysql = require("mysql")
var app = express();
const option = {
    host: 'localhost',
    user: 'root',
    password: 'root',
    port: '3306',
    database: 'data',
    connectTimeout: 5000,
    multipeStatements: false
}
const conn = mysql.createConnection(option)
//解决跨域问题
const cors = require('cors');
// 中间件 获取参数的
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());


app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OP0TIONS");
    res.header("X-Powered-By", "3.2.1");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
var url = "";
//查询轮播图数据
app.get('/RotationMap', (req, res) => {
    conn.query(
        ' SELECT * FROM rotationmap order by id',
        function (err, result) {
            res.json(new Result({ data: result }))
        }
    );

});

//查询小兔子数据
app.get('/rabbit', (req, res) => {
    conn.query(' SELECT url FROM rabbit order by id', (e, r) => res.json(new Result({ data: r })));
});
// // 添加数据
// function Result({ data = {} }) {
//     this.url = data;
// }
//查询英文数据
app.get('/english', function (req, res) {
    conn.query(' SELECT url FROM english order by id', (e, r) => res.json(new Result({ data: r })));

});
//查询大猩猩数据
app.get('/monkey', function (req, res) {
    conn.query(' SELECT url FROM monkey order by id', (e, r) => res.json(new Result({ data: r })));

});

//查询爱丽丝数据
app.get('/beauty', function (req, res) {
    conn.query(' SELECT url FROM beauty order by id', (e, r) => res.json(new Result({ data: r })));

});

//查询美女数据
app.get('/Jordan', function (req, res) {
    conn.query(' SELECT url FROM Jordan order by id', (e, r) => res.json(new Result({ data: r })));

});
// 添加数据
function Result({ data = {} }) {
    this.url = data;
}


//微信登陆
app.post('/login', function (req, res) {

    res.status(200)
    var dataWx = null;
    let appid = 'wxda75ca6ab28e5c6e'
    let secret = 'e52be9bfc1fe5f667de3d9a4bc2b2cee'
    let code = JSON.parse(res.req.body.info).code
    let nickName = JSON.parse(res.req.body.info).nickName
    request({
        method: 'GET',
        url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`,
        headers: {
            // 'Content-Type': 'application/json',
            // 'X-Requested-With': 'XMLHttpRequest',
        },
        // 请求和回发的数据自动转变成了 json 对象
        // 不需要在header中设置'Content-Type': 'application/json',也不需要手动JSON.stringify()转义Body postdata
        json: true,
        body: {
            'openid': '',
            'session_key': '',
            'unionid': '',
            'errcode': '',
            'errmsg': ''
        },
    }, function (err, response, body) {
        console.log(body);
        conn.query(
            ' SELECT openid FROM user ',
            function (err, result) {
                let flag = false
                for (let i = 0; i < result.length; i++) {
                    if (result[i].openid == body.openid) {
                        flag = true;
                        conn.query(`
                    UPDATE user SET UserName="${nickName}",UpdatedTime=Now() WHERE openid="${body.openid}"
                            `
                        );
                    }
                }
                if (!flag) {
                    conn.query(` INSERT INTO user (UserName, openid) VALUES("${nickName}", "${body.openid}")`
                    );
                }


            }
        );



    })


    //传入页面 
    res.send()
});

app.listen(8888, function () {
    console.log("服务器启动成功了端口是", 8888);
})